package wheel

import (
	"container/list"
	"sync"
	"time"
)

type TimeWheel struct {
	Scale         int //刻度
	Current       int //当前索引
	Size          int //个数
	stopChan      chan struct{}
	WheelTaskList sync.Map
}

type Task struct {
	task  func()
	index int
	cycle int
}

func NewWheel(scale, size int) *TimeWheel {
	return &TimeWheel{
		Scale:   scale,
		Current: 0,
		Size:    size,
	}
}

func (t *TimeWheel) Add(fn func(), target int, cycle int) {
	var task = &Task{
		task:  fn,
		index: target,
		cycle: cycle,
	}
	wheelTaskList, ok := t.WheelTaskList.Load(target)
	if ok {
		wheelTaskList.(*list.List).PushFront(task)
	} else {
		taskList := list.New()
		taskList.PushFront(task)
		t.WheelTaskList.Store(target, taskList)
	}
}

func (t *TimeWheel) Start() {
	tm := time.NewTicker(time.Second)
	for {
		select {

		case <-tm.C:
			DefaultLogger.Info("每秒一次")
			if t.Current == t.Size-1 {
				t.Current = 0
			} else {
				t.Current++
			}
			taskList, ok := t.WheelTaskList.Load(t.Current)
			if ok {
				el := taskList.(*list.List).Front()
				for el != nil {
					task := el.Value.(*Task)
					if task.cycle == 0 {
						task.task()
						el = el.Next()
					}

					task.cycle--
				}
			}

		}
	}

}
